package com.yyz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yyz.common.BaseContext;
import com.yyz.domain.*;
import com.yyz.dto.OrdersDto;
import com.yyz.exception.CustomException;
import com.yyz.mapper.*;
import com.yyz.service.OrdersService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author yyz
 * @create 2023-07-27 16:37
 */
@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    /**
     * 支付
     *
     * @param orders
     */
    @Override
    @Transactional
    public void submit(Orders orders) {
        //获取用户id
        Long userId = BaseContext.getThreadLocal();

        //根据id查询购物车
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId, userId);

        List<ShoppingCart> ShoppingCarts = shoppingCartMapper.selectList(lqw);

        //购物车为空，抛业务异常
        if (ShoppingCarts == null) {
            throw new CustomException("购物车为空！");
        }

        //查询用户数据
        User user = userMapper.selectById(userId);

        //查询地址数据
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookMapper.selectById(addressBookId);
        if (addressBook == null) {
            throw new CustomException("用户地址信息有误，不能下单");
        }

        long orderId = IdWorker.getId();//订单号

        AtomicInteger amount = new AtomicInteger(0);
        ArrayList<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart shoppingCart : ShoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);//设置订单号
            orderDetail.setNumber(shoppingCart.getNumber());//设置数量
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());//设置口味
            orderDetail.setDishId(shoppingCart.getDishId());//设置菜品id
            orderDetail.setSetmealId(shoppingCart.getSetmealId());//设置套餐id
            orderDetail.setName(shoppingCart.getName());//设置名称
            orderDetail.setImage(shoppingCart.getImage());//设置图片
            orderDetail.setAmount(shoppingCart.getAmount());//设置单个金额

            orderDetails.add(orderDetail);
            //计算总金额
            amount.addAndGet(shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber())).intValue());
        }

        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());//设置下单时间
        orders.setCheckoutTime(LocalDateTime.now());//设置结账时间
        orders.setStatus(2);//设置订单状态
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(userId);//设置用户id
        orders.setNumber(String.valueOf(orderId));//设置订单号
        orders.setUserName(user.getName());//设置用户名
        orders.setConsignee(addressBook.getConsignee());//设置收货人
        orders.setPhone(addressBook.getPhone());//设置手机号
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));

        //添加进订单表
        ordersMapper.insert(orders);

        //添加购物车菜品进订单明细表
        for (OrderDetail orderDetail : orderDetails) {
            orderDetailMapper.insert(orderDetail);
        }

        //清空购物车
        shoppingCartMapper.delete(lqw);
    }

    /**
     * 查询订单(手机端)
     *
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public IPage<OrdersDto> list(Integer page, Integer pageSize) {
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        Page<OrdersDto> pageInfo = new Page<>();

        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.orderByDesc(Orders::getOrderTime);

        ordersMapper.selectPage(ordersPage, lqw);

        BeanUtils.copyProperties(ordersPage, pageInfo, "records");
        ArrayList<OrdersDto> ordersDtos = new ArrayList<>();
        for (Orders record : ordersPage.getRecords()) {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(record, ordersDto);

            Long id = record.getId();

            LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(OrderDetail::getOrderId, id);
            List<OrderDetail> orderDetails = orderDetailMapper.selectList(wrapper);

            ordersDto.setOrderDetails(orderDetails);

            ordersDtos.add(ordersDto);
        }
        pageInfo.setRecords(ordersDtos);

        return pageInfo;
    }

    /**
     * 查询订单(pc端)
     *
     * @param page
     * @param pageSize
     * @param number
     * @param begin
     * @param end
     * @return
     */
    @Override
    public IPage<OrdersDto> pageList(Integer page, Integer pageSize, Long number, LocalDate begin, LocalDate end) {
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        Page<OrdersDto> pageInfo = new Page<>();

        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.eq(number != null, Orders::getNumber, number)
                .between(begin != null && end != null, Orders::getOrderTime, begin, end)
                .orderByDesc(Orders::getOrderTime);

        ordersMapper.selectPage(ordersPage, lqw);
        BeanUtils.copyProperties(ordersPage,pageInfo,"records");

        List<Orders> records = ordersPage.getRecords();
        ArrayList<OrdersDto> ordersDtos = new ArrayList<>();
        for (Orders record : records) {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(record,ordersDto);

            Long userId = record.getUserId();
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getId,userId);

            User user = userMapper.selectOne(wrapper);
            ordersDto.setUserName(user.getName());
            ordersDtos.add(ordersDto);
        }

        pageInfo.setRecords(ordersDtos);

        return pageInfo;
    }

    /**
     * 派送
     * @param orders
     */
    @Override
    public void status(Orders orders) {
        ordersMapper.updateById(orders);
    }
}
